# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        fast,slow = head,head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                break
        if not fast or not fast.next:
            return None
        slow = head
        while fast != slow:
            fast = fast.next
            slow = slow.next
        return slow


    def detectCycle2(self, head: Optional[ListNode]) -> Optional[ListNode]:
        setList = set()
        if head in setList:
            return head
            setList.add(head)
            head = head.next
        else:
            return None
